<template>
  <section class="space-y-4 pb-16">
    <!-- 筛选条件区域 -->
    <div class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
      <!-- 时间筛选 -->
      <div class="space-y-3">
        <!-- 范围时间选择 -->
        <div class="grid grid-cols-2 gap-2">
          <input type="date" v-model="startDate" 
                 @change="handleDateChange"
                 :min="minDate" :max="maxDate"
                 placeholder="开始日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent">
          <input type="date" v-model="endDate"
                 @change="handleDateChange"
                 :min="minDate" :max="maxDate"
                 placeholder="结束日期"
                 class="px-3 py-2 border border-gray-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-green-500 focus:border-transparent">
        </div>

        <!-- 快捷时间选项 -->
        <div class="flex gap-1">
          <button v-for="option in quickOptions" :key="option.value" 
                  @click="selectQuickOption(option.value)"
                  :class="[
                    'px-3 py-1.5 rounded text-sm font-medium transition-all whitespace-nowrap flex-1',
                    quickTime === option.value 
                      ? 'bg-green-500 text-white border border-green-500' 
                      : 'bg-gray-50 text-gray-600 hover:bg-gray-100 border border-gray-200'
                  ]">
            {{ option.label }}
          </button>
        </div>
      </div>

      <!-- 场站筛选 -->
      <div class="flex items-center justify-between mt-4 pt-4 border-t border-gray-100">
        <div class="text-sm font-medium text-gray-700">场站筛选</div>
        <div class="relative">
          <button @click="toggleSitePicker($event)"
                  class="inline-flex items-center gap-1 px-3 py-1.5 border border-gray-200 bg-white rounded-md text-sm text-gray-700 hover:bg-gray-50 shadow-sm">
            <span class="truncate max-w-[180px]">{{ selectedSiteName }}</span>
            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-4 h-4 text-gray-500"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 9l6 6 6-6"/></svg>
          </button>
          <!-- 场站下拉选择 -->
          <div v-if="showSitePicker" v-click-outside="closeSitePicker" class="absolute right-0 top-full mt-2 z-20 rounded-lg bg-white text-gray-900 shadow-lg ring-1 ring-black/5 max-h-[12rem] overflow-y-auto">
            <button class="block w-full text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectSite(null)">全部场站</button>
            <div>
              <button v-for="s in sites" :key="s.stationId" class="block w-full text-left px-3 py-2 hover:bg-gray-50 text-sm whitespace-nowrap" @click="selectSite(s.stationId)">
                {{ s.stationName }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="bg-gradient-to-r from-green-500 to-emerald-600 text-white rounded-2xl p-5 shadow-glass">
      <div class="text-center">
        <div class="text-sm text-white/80 mb-1">累计入账</div>
        <div class="text-3xl font-bold">¥ {{ totalIncome.toFixed(2) }}</div>
        <div class="text-xs text-white/70 mt-1">共 {{ filteredRecords.length }} 笔入账</div>
      </div>
    </div>

    <!-- 记录数量统计 -->
    <div class="flex justify-between items-center">
      <div class="text-sm text-gray-500">筛选结果</div>
      <div class="text-sm text-gray-500">共 {{ filteredRecords.length }} 条记录</div>
    </div>

    <!-- 记录列表 -->
    <div class="space-y-3">
      <!-- 加载状态 -->
      <div v-if="loading" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
        <div class="flex flex-col items-center justify-center space-y-3">
          <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-green-500"></div>
          <div class="text-gray-500 text-sm">正在加载数据...</div>
        </div>
      </div>
      
      <!-- 错误状态 -->
      <div v-else-if="errorMessage" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
        <div class="flex flex-col items-center justify-center space-y-3">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-red-500">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M12 9v3.75m-9.303 3.376c-.866 1.5.217 3.374 1.948 3.374h14.71c1.73 0 2.813-1.874 1.948-3.374L13.949 3.378c-.866-1.5-3.032-1.5-3.898 0L2.697 16.126zM12 15.75h.007v.008H12v-.008z"/>
          </svg>
          <div class="text-red-500 text-sm">{{ errorMessage }}</div>
          <button @click="loadData" class="text-sm bg-green-500 text-white px-4 py-2 rounded-lg hover:bg-green-600 transition-colors">
            重新加载
          </button>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-else-if="filteredRecords.length === 0" class="bg-white rounded-lg p-8 shadow-sm border border-gray-100 text-center">
        <div class="flex flex-col items-center justify-center space-y-3">
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" class="w-12 h-12 text-gray-300">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"/>
          </svg>
          <div class="text-gray-500 text-sm">暂无符合条件的入账记录</div>
          <div class="text-gray-400 text-xs">请尝试调整筛选条件</div>
        </div>
      </div>
      
      <!-- 数据列表 -->
      <div v-else v-for="record in filteredRecords" :key="record.profitStatisticId" class="bg-white rounded-2xl p-4 shadow-sm border border-gray-100">
        <!-- 场站和日期信息 -->
        <div class="flex items-center justify-between mb-4">
          <div>
            <div class="font-medium text-gray-900">{{ record.stationName }}</div>
            <div class="text-xs text-gray-500">{{ formatDate(record.inComeTime) }}</div>
          </div>
          <div class="text-right">
            <div class="text-lg font-semibold text-green-600">+{{ record.actualIncome.toFixed(2) }}</div>
            <div class="text-xs text-gray-500">服务费分成</div>
          </div>
        </div>
        
        <!-- 详细统计信息 -->
        <div class="grid grid-cols-4 gap-1.5 mb-3">
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">总服务费</div>
            <div class="text-sm font-medium text-gray-900">{{ record.serviceFeeTotal.toFixed(2) }}</div>
          </div>
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">订单数</div>
            <div class="text-sm font-medium text-gray-900">{{ record.ordersCount }}</div>
          </div>
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">分成比例</div>
            <div class="text-sm font-medium text-gray-900">{{ record.shareRatio }}%</div>
          </div>
          <div class="bg-gray-50 rounded-lg p-2.5 text-center min-w-0">
            <div class="text-xs text-gray-500 mb-1 whitespace-nowrap overflow-hidden">实际收入</div>
            <div class="text-sm font-medium text-gray-900">{{ record.actualIncome.toFixed(2) }}</div>
          </div>
        </div>
        
        <!-- 运营商信息 -->
        <div class="text-xs text-gray-600 bg-gray-50 rounded-lg p-2">
          <div class="flex justify-between">
            <span>运营商：</span>
            <span class="font-medium">{{ record.orgName }}</span>
          </div>
          <div class="flex justify-between mt-1">
            <span>统计时间：</span>
            <span>{{ record.inComeTime }}</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载更多 -->
    <div class="text-center py-4">
      <button v-if="hasMore && !loading" @click="loadMore" class="text-sm text-gray-600 hover:text-gray-900 px-4 py-2 border border-gray-200 rounded-lg hover:border-gray-300 transition-colors">
        加载更多记录
      </button>
      <div v-else-if="!hasMore" class="text-sm text-gray-500">没有更多记录了</div>
    </div>
  </section>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { getIncomeRecords } from '../api/my'
import { getSimpleStationList } from '../api/station'

const router = useRouter()

const goBack = () => {
  router.push('/mine')
}

// 点击外部关闭下拉菜单的自定义指令
const vClickOutside = {
  mounted(el, binding) {
    el._clickOutsideHandler = (event) => {
      if (!(el === event.target || el.contains(event.target))) {
        binding.value(event)
      }
    }
    document.addEventListener('click', el._clickOutsideHandler)
  },
  unmounted(el) {
    document.removeEventListener('click', el._clickOutsideHandler)
  }
}

// 状态管理
const loading = ref(false)
const errorMessage = ref('')
const apiData = ref({
  cumulative: 0,
  total: 0,
  list: []
})
const hasMore = ref(true)
const lastId = ref('')

// 时间筛选相关
const startDate = ref('')
const endDate = ref('')
const quickTime = ref('today')
const showSitePicker = ref(false)
const selectedSiteId = ref('')
const selectedSite = computed(() => sites.value?.find(s => s.stationId === selectedSiteId.value) || null)

// 快捷时间选项
const quickOptions = [
  { label: '今天', value: 'today' },
  { label: '昨天', value: 'yesterday' },
  { label: '近7天', value: 'week' },
  { label: '全部', value: 'all' }
]

// 场站数据 - 通过API获取，与首页、订单页保持一致
const sites = ref([])

// 选中场站显示名称
const selectedSiteName = computed(() => {
  if (!selectedSiteId.value) {
    return '全部场站'
  }
  const site = selectedSite.value
  return site ? site.stationName : '选择场站'
})

// 计算属性
const totalIncome = computed(() => apiData.value.cumulative || 0)

const filteredRecords = computed(() => {
  // 直接返回API返回的数据，后端已经完成了场站筛选
  return apiData.value.list || []
})

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 切换场站选择器显示状态
const toggleSitePicker = (event) => {
  if (event) event.stopPropagation() // 阻止事件冒泡
  showSitePicker.value = !showSitePicker.value
}

// 关闭场站选择器
const closeSitePicker = () => {
  showSitePicker.value = false
}

// 获取场站列表
const fetchStationList = async () => {
  try {
    console.log('开始获取场站列表...')
    const response = await getSimpleStationList()
    console.log('场站列表API响应:', JSON.stringify(response))
    
    if (response.success && response.data && response.data.list) {
      // 直接使用API返回的数据结构，不需要转换
      sites.value = response.data.list
      console.log('场站列表数据:', sites.value)
    } else {
      console.error('获取场站列表失败:', response.message || '未知错误')
      sites.value = []
    }
  } catch (error) {
    console.error('获取场站列表异常:', error)
    sites.value = []
  }
}

// 选择场站
const selectSite = (siteId) => {
  selectedSiteId.value = siteId
  showSitePicker.value = false
  console.log('选择站点:', siteId, '站点名称:', siteId ? sites.value?.find(s => s.stationId === siteId)?.stationName : '全部场站')
  // 选择站点后重新加载数据
  loadData(true)
}

// 选择快捷时间
const selectQuickOption = (value) => {
  quickTime.value = value
  // 根据快捷时间设置日期范围
  const today = new Date()
  switch (value) {
    case 'today':
      startDate.value = today.toISOString().split('T')[0]
      endDate.value = today.toISOString().split('T')[0]
      break
    case 'yesterday':
      const yesterday = new Date(today)
      yesterday.setDate(yesterday.getDate() - 1)
      startDate.value = yesterday.toISOString().split('T')[0]
      endDate.value = yesterday.toISOString().split('T')[0]
      break
    case 'week':
      // 近7天：今天 + 前6天，共7天
      const weekAgo = new Date(today)
      weekAgo.setDate(today.getDate() - 6)
      startDate.value = weekAgo.toISOString().split('T')[0]
      endDate.value = today.toISOString().split('T')[0]
      break
    case 'all':
      // 全部：设置从2025年1月1日到今天
      startDate.value = '2025-01-01'
      endDate.value = today.toISOString().split('T')[0]
      break
  }
  // 重新加载数据
  loadData(true)
}

// 处理日期变化
const handleDateChange = () => {
  quickTime.value = ''
  loadData(true)
}

// 加载数据
const loadData = async (reset = false) => {
  if (reset) {
    lastId.value = ''
    hasMore.value = true
  }
  
  loading.value = true
  errorMessage.value = ''
  
  try {
    const params = {
      lastId: lastId.value,
      stationId: selectedSiteId.value === '' ? '' : selectedSiteId.value,
      startTime: startDate.value ? startDate.value + ' 00:00:00' : '',
      endTime: endDate.value ? endDate.value + ' 23:59:59' : ''
    }
    
    console.log('请求参数:', params)
    
    const response = await getIncomeRecords(params)
    
    console.log('入账记录API响应:', JSON.stringify(response))
    
    if (response.success) {
      if (reset) {
        apiData.value = response.data || { cumulative: 0, total: 0, list: [] }
      } else {
        // 追加数据
        if (response.data && response.data.list) {
          apiData.value.list = [...apiData.value.list, ...response.data.list]
          apiData.value.cumulative = response.data.cumulative || apiData.value.cumulative
          apiData.value.total = response.data.total || apiData.value.total
        }
      }
      
      // 更新lastId和hasMore状态
      if (response.data && response.data.list && response.data.list.length > 0) {
        lastId.value = response.data.list[response.data.list.length - 1].profitStatisticId
        hasMore.value = response.data.list.length >= 10 // 假设每页10条
      } else {
        hasMore.value = false
      }
      
      console.log('数据加载成功:', apiData.value)
    } else {
      errorMessage.value = response.message || '获取数据失败'
      console.error('获取数据失败:', response.message)
    }
  } catch (error) {
    errorMessage.value = '网络错误，请检查网络连接'
    console.error('获取数据异常:', error)
  } finally {
    loading.value = false
  }
}

// 加载更多
const loadMore = () => {
  loadData(false)
}

// 初始化日期范围
const minDate = '2024-01-01'
const maxDate = '2024-12-31'

onMounted(() => {
  // 设置默认日期为今天
  const today = new Date().toISOString().split('T')[0]
  startDate.value = today
  endDate.value = today
  
  // 获取场站列表
  fetchStationList()
  
  // 加载数据
  loadData(true)
})
</script>